package com.g.jnitext;


import android.util.Log;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 串口操作类
 *
 * Serial port operation class
 */
public class SerialPortModel {

    private static final String LOG_TAG = SerialPortModel.class.getSimpleName();

    private FileDescriptor mFd;
    private FileInputStream mFileInputStream;
    private FileOutputStream mFileOutputStream;

    /**
     * 打开串口
     *
     * Open the serial port
     */
    public SerialPortModel(File device, int baudRate, int dataBits,
                           String checkingMode, int stopBits, String flowMode)
            throws SecurityException, IOException {

        //todo 由于系统升级为5.1.1版本，不能用之前的su去获取权限打开串口，只能再AndroidManifest添加android:sharedUserId="android.uid.system"
        //todo 然后再用系统签名打包，这样app变成系统应用才有权限去打开串口
		/* Check permission */
//        if (!device.canRead() || !device.canWrite()) {
//            try {
//				/* Can't read/write this device,then try to chmod permission */
//                Process su;
//                su = Runtime.getRuntime().exec("/system/bin/su");
//                String cmd = "chmod 666 " + device.getAbsolutePath() + "\n"
//                        + "exit\n";
//                su.getOutputStream().write(cmd.getBytes());
//                if ((su.waitFor() != 0) || !device.canRead()
//                        || !device.canWrite()) {
//                    throw new SecurityException("Can't root!");
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//                throw new SecurityException();
//            }
//        }

        mFd = open(device.getAbsolutePath(), baudRate,dataBits,checkingMode,stopBits,flowMode);
        if (mFd == null) {
            Log.e("SerialPortModel","串口打开失败：NULL");
            Log.e(LOG_TAG, "Error:Open serial device faile.");
            throw new IOException();
        }
        mFileInputStream = new FileInputStream(mFd);
        mFileOutputStream = new FileOutputStream(mFd);
    }

    public InputStream getInputStream() {
        return mFileInputStream;
    }

    public OutputStream getOutputStream() {
        return mFileOutputStream;
    }

    private native static FileDescriptor open(String path, int baudrate, int dataBits, String checkingMode, int stopBits, String flowMode);
    public native void close();

    //todo 此处可能会报一个错误，找不到serial_port.so，在之前的4.2系统是可以的，到5.1.1就不行，可以试试不用mylibrary （把cpp文件放进测试项目里，改成像百软通那样的）
    static {
//        serial_port
      //  System.loadLibrary("serial_port");
    }
}
